from doas.io import UnableToLoad, register
from doas.spec import Spectrum
import numpy
import datetime
import re


class STDPlugin:
    def __init__(self):
        self.name = "DOASIS STD"
    
    def test(self, fp):
        try:
            if fp.read(8) == 'GDBGMNUP':
                return True
            else:
                return False
        except:
            return False
    
    
    def load(self, fp):
        #skip the first two lines
        fp.readline()
        fp.readline()
        
        n_pix = int(fp.readline())
        
        #now read all the pixel data
        counts = numpy.fromfile(fp, count=n_pix, sep='\n')  
        
        #sanity check that we managed to load as much data as we wanted
        if counts.shape[0] != n_pix:
            raise UnableToLoad("Data loaded is wrong length")

        
        #load all the header data
        header = fp.read()
        
        #get the capture time
        date_re = "^((?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<year>\d{4,4}))"
        time_re = "^((?P<hour>\d{1,2}):(?P<minute>\d{1,2}):(?P<second>\d{1,2}))"
        
        #read the date from the file
        d = re.search(date_re,header,flags=re.MULTILINE)
        if d is None:
            raise ValueError, "Failed to read the date from the file"
        d = d.groupdict() 
        
        #read the time from the file
        t = re.search(time_re,header,flags=re.MULTILINE)
        if t is None:
            raise ValueError, "Failed to read the time from the file"    
        t = t.groupdict() 
            
        #build a datetime object
        capture_time = datetime.datetime(int(d["year"]),int(d["month"]),
                                         int(d["day"]),int(t["hour"]),
                                         int(t["minute"]),int(t["second"]))
        
        
        #get the spectrometer id
        device_re = r'^Device = "(?P<spec_id>.+)"'
        id = re.search(device_re,header,flags=re.MULTILINE)
        if id is None:
            raise ValueError, "Failed to read the device id from the file"
        spectrometer_id = id.groupdict()['spec_id']
        
        #get the integration time
        int_time_re = r'^ExposureTime = (?P<int_time>[0-9]*\.?[0-9]*)'
        int_time = re.search(int_time_re,header,flags=re.MULTILINE)
        if int_time is None:
            raise ValueError, "Failed to read the integration time from the file"
        int_time = float(int_time.groupdict()['int_time']) / 1000.0 #in seconds
        
        #get the number of scans
        scans_re = r'^NumScans = (?P<scans>[0-9]*)'
        scans = re.search(scans_re,header,flags=re.MULTILINE)
        if scans is None:
            raise ValueError, "Failed to read the number of scans from the file"
        n_avg = int(scans.groupdict()['scans']) #in seconds
        
        wavelengths = [] #TODO
        return Spectrum(fp.name, wavelengths, counts, capture_time, spectrometer_id,
                        int_time, n_avg)


register(STDPlugin()) 